package com.shigen.demo.atguigu;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁
 *
 * @author shigenfu
 * @date 2022/5/22 4:06 下午
 */
class Phone implements Runnable {

  public synchronized void sendSMS() {
    System.out.println(Thread.currentThread().getName() + "  sendSMS......");
    sendEmail();
  }

  public synchronized void sendEmail() {
    System.out.println(Thread.currentThread().getName() + "   sendEmail.....");
  }


  Lock lock = new ReentrantLock();

  @Override
  public void run() {
    get();
  }

  private void get() {
    try {
      lock.lock();
      System.out.println(Thread.currentThread().getName() + " get.....");
      set();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  private void set() throws Exception {
    try {
      lock.lock();
      System.out.println(Thread.currentThread().getName() + " set.....");
    } finally {
      lock.unlock();
    }

  }
}


public class ReenterLockDemo {

  public static void main(String[] args) {
    Phone phone = new Phone();
    new Thread(() -> {
      phone.sendSMS();
    }, "t1").start();

    new Thread(() -> {
      phone.sendSMS();
    }, "t2").start();

    try {
      TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    Thread t3 = new Thread(phone);
    Thread t4 = new Thread(phone);

    t3.start();
    t4.start();


  }
}
